package com.moment.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.json.JSONException;
import org.json.JSONObject;

public class Converter {

	public static String listToString(List list) {
		Gson gson = new Gson();
		String json = gson.toJson(list);
		return json;
	}
	public String mapToJson(Map<String,String> map) {
		ObjectMapper mapper = new ObjectMapper();
		String json=null;
	try {
		if(map.containsKey("method")){
			json="[{\"method\":\""+map.get("method")+"\"},";
			map.remove("method");
		}
		json += mapper.writeValueAsString(map)+"]";
		//System.out.println(" mapToJson : json String "+json);
		return json;
	} catch (JsonGenerationException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		return null;
	} catch (JsonMappingException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		return null;
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		return null;
	}
		

	}
	
	
	public static void main(String args[]){
	/*	Map<String,String> map=new HashMap<String, String>();
		map.put("method", "0");
		map.put("name", "mitul");
		System.out.println("map:"+map);
		
		List<String> list=new ArrayList<String>();
		list.add("name");
		list.add("mitul");
		System.out.println("list:"+list);
		System.out.println("json of list:"+listToString(list));
		
		*/
		
		
		Map<String,String > map=new HashMap<String,String >();
		
		map.put("method", "5");
		map.put("loginid", "mitul");
		map.put("password", "password");
		
		System.out.println("json String:"+new Converter().mapToJson(map));
	}

	
	public static Map<String,String> parse(JSONObject json , Map<String,String> out) throws JSONException{
	    Iterator<String> keys = json.keys();
	    while(keys.hasNext()){
	        String key = keys.next();
	        String val = null;
	        try{
	             JSONObject value = json.getJSONObject(key);
	             System.out.println(" key:"+key +" val:"+value);
	             parse(value,out);
	        }catch(Exception e){
	            val = json.getString(key);
	        }

	        if(val != null){
	            out.put(key,val);
	        }
	    }
	    return out;
	}

}
